package com.fzf.org.toolkit;

import com.fzf.org.config.TXSliderConfig;
import com.tencentcloudapi.captcha.v20190722.CaptchaClient;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultRequest;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class SliderCheckService {

    private final TXSliderConfig txSliderConfig;
    private Credential cred;

    @PostConstruct
    public void init() {
        this.cred = new Credential(txSliderConfig.getSecretId(), txSliderConfig.getSecretKey());
    }
    public boolean checkSlider(String ticket, String randStr, String userIp) {
        try {
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("captcha.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            CaptchaClient client = new CaptchaClient(this.cred, "", clientProfile);
            DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest();
            req.setCaptchaType(this.txSliderConfig.getCaptchaType());
            req.setCaptchaAppId(this.txSliderConfig.getCaptchaAppId());
            req.setAppSecretKey(this.txSliderConfig.getAppSecretKey());

            req.setTicket(ticket);
            req.setRandstr(randStr);
            req.setUserIp(userIp);

            DescribeCaptchaResultResponse resp = client.DescribeCaptchaResult(req);
            return resp.getCaptchaCode() == 0;
        } catch (TencentCloudSDKException e) {
            log.error("远程检验滑快验证码失败，错误：", e);
        }
        return false;
    }
}
